//=========================================================================
// Copyright (C) 2024 The C++ Component Model(COMO) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================

#include <assert.h>
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdarg.h>
#include "tlsf.h"

//#define __DEBUG__ 1

#if defined(__cplusplus)
#define TLSF_DECL inline
#else
#define TLSF_DECL static
#endif

/*
** Architecture-specific bit manipulation routines.
**
** TLSF achieves O(1) cost for malloc and free operations by limiting
** the search for a free block to a free list of guaranteed size
** adequate to fulfill the request, combined with efficient free list
** queries using bitmasks and architecture-specific bit-manipulation
** routines.
**
** Most modern processors provide instructions to count leading zeroes
** in a word, find the lowest and highest set bit, etc. These
** specific implementations will be used when available, falling back
** to a reasonably efficient generic implementation.
**
** NOTE: TLSF spec relies on ffs/fls returning value 0..31.
** ffs/fls return 1-32 by default, returning 0 for error.
*/

/*
** Detect whether or not we are building for a 32- or 64-bit (LP/LLP)
** architecture. There is no reliable portable method at compile-time.
*/
#if defined (__alpha__) || defined (__ia64__) || defined (__x86_64__) \
    || defined (_WIN64) || defined (__LP64__) || defined (__LLP64__)
#define TLSF_64BIT
#endif

/*
** gcc 3.4 and above have builtin support, specialized for architecture.
** Some compilers masquerade as gcc; patchlevel test filters them out.
*/
#if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \
    && defined (__GNUC_PATCHLEVEL__)

#if defined (__SNC__)
/* SNC for Playstation 3. */

TLSF_DECL int tlsf_ffs(unsigned int word)
{
    const unsigned int reverse = word & (~word + 1);
    const int bit = 32 - __builtin_clz(reverse);
    return bit - 1;
}

#else

TLSF_DECL int tlsf_ffs(unsigned int word)
{
    return __builtin_ffs(word) - 1;
}

#endif

TLSF_DECL int tlsf_fls(unsigned int word)
{
    int bit;

    //const int bit = word ? 32 - __builtin_clz(word) : 0;
    if (0 != word) {
        bit = 32 - __builtin_clz(word);
    }
    else {
        bit = 0;
    }

    return bit - 1;
}

#elif defined (_MSC_VER) && (_MSC_VER >= 1400) && (defined (_M_IX86) || defined (_M_X64))
/* Microsoft Visual C++ support on x86/X64 architectures. */

#include <intrin.h>

#pragma intrinsic(_BitScanReverse)
#pragma intrinsic(_BitScanForward)

TLSF_DECL int tlsf_fls(unsigned int word)
{
    unsigned long index;
    return _BitScanReverse(&index, word) ? index : -1;
}

TLSF_DECL int tlsf_ffs(unsigned int word)
{
    unsigned long index;
    return _BitScanForward(&index, word) ? index : -1;
}

#elif defined (_MSC_VER) && defined (_M_PPC)
/* Microsoft Visual C++ support on PowerPC architectures. */

#include <ppcintrinsics.h>

TLSF_DECL int tlsf_fls(unsigned int word)
{
    const int bit = 32 - _CountLeadingZeros(word);
    return bit - 1;
}

TLSF_DECL int tlsf_ffs(unsigned int word)
{
    const unsigned int reverse = word & (~word + 1);
    const int bit = 32 - _CountLeadingZeros(reverse);
    return bit - 1;
}

#elif defined (__ARMCC_VERSION)
/* RealView Compilation Tools for ARM */

TLSF_DECL int tlsf_ffs(unsigned int word)
{
    const unsigned int reverse = word & (~word + 1);
    const int bit = 32 - __clz(reverse);
    return bit - 1;
}

TLSF_DECL int tlsf_fls(unsigned int word)
{
    const int bit = word ? 32 - __clz(word) : 0;
    return bit - 1;
}

#elif defined (__ghs__)
/* Green Hills support for PowerPC */

#include <ppc_ghs.h>

TLSF_DECL int tlsf_ffs(unsigned int word)
{
    const unsigned int reverse = word & (~word + 1);
    const int bit = 32 - __CLZ32(reverse);
    return bit - 1;
}

TLSF_DECL int tlsf_fls(unsigned int word)
{
    const int bit;

    // bit = word ? 32 - __CLZ32(word) : 0;
    if (0 != word) {
        bit = 32 - __CLZ32(word);
    }
    else {
        bit = 0;
    }

    return bit - 1;
}

#else
/* Fall back to generic implementation. */

TLSF_DECL int tlsf_fls_generic(unsigned int word)
{
    int bit = 32;

    if (0 == word) {
        bit -= 1;
    }

    if (0 == (word & 0xffff0000u)) {
        word <<= 16;
        bit -= 16;
    }

    if (0 == (word & 0xff000000u)) {
        word <<= 8;
        bit -= 8;
    }

    if (0 == (word & 0xf0000000u)) {
        word <<= 4;
        bit -= 4;
    }

    if (0 == (word & 0xc0000000u)) {
        word <<= 2;
        bit -= 2;
    }

    if (0 == (word & 0x80000000u)) {
        word <<= 1;
        bit -= 1;
    }

    return bit;
}

/* Implement ffs in terms of fls. */
TLSF_DECL int tlsf_ffs(unsigned int word)
{
    return tlsf_fls_generic(word & (~word + 1)) - 1;
}

TLSF_DECL int tlsf_fls(unsigned int word)
{
    return tlsf_fls_generic(word) - 1;
}

#endif

/* Possibly 64-bit version of tlsf_fls. */
#if defined (TLSF_64BIT)
TLSF_DECL int tlsf_fls_sizet(size_t size)
{
    int high = (int)(size >> 32);
    int bits = 0;

    if (high) {
        bits = 32 + tlsf_fls(high);
    }
    else {
        bits = tlsf_fls((int)size & 0xffffffff);
    }
    return bits;
}
#else
#define tlsf_fls_sizet tlsf_fls
#endif

#undef TLSF_DECL

/*
** Constants.
*/

/* Public constants: may be modified. */
enum tlsf_public
{
    /* log2 of number of linear subdivisions of block sizes. Larger
    ** values require more memory in the control structure. Values of
    ** 4 or 5 are typical.
    */
    SL_INDEX_COUNT_LOG2 = 5,
};

/* Private constants: do not modify. */
enum tlsf_private
{
#if defined (TLSF_64BIT)
    /* All allocation sizes and addresses are aligned to 8 bytes. */
    ALIGN_SIZE_LOG2 = 3,
#else
    /* All allocation sizes and addresses are aligned to 4 bytes. */
    ALIGN_SIZE_LOG2 = 2,
#endif
    ALIGN_SIZE = (1 << ALIGN_SIZE_LOG2),

    /*
    ** We support allocations of sizes up to (1 << FL_INDEX_MAX) bits.
    ** However, because we linearly subdivide the second-level lists, and
    ** our minimum size granularity is 4 bytes, it doesn't make sense to
    ** create first-level lists for sizes smaller than SL_INDEX_COUNT * 4,
    ** or (1 << (SL_INDEX_COUNT_LOG2 + 2)) bytes, as there we will be
    ** trying to split size ranges into more slots than we have available.
    ** Instead, we calculate the minimum threshold size, and place all
    ** blocks below that size into the 0th first-level list.
    */

#if defined (TLSF_64BIT)
    /*
    ** TODO: We can increase this to support larger sizes, at the expense
    ** of more overhead in the TLSF structure.
    */
    FL_INDEX_MAX = 32,
#else
    FL_INDEX_MAX = 30,
#endif
    SL_INDEX_COUNT = (1 << SL_INDEX_COUNT_LOG2),
    FL_INDEX_SHIFT = (SL_INDEX_COUNT_LOG2 + ALIGN_SIZE_LOG2),
    FL_INDEX_COUNT = (FL_INDEX_MAX - FL_INDEX_SHIFT + 1),

    SMALL_BLOCK_SIZE = (1 << FL_INDEX_SHIFT),
};

/*
** Cast and min/max macros.
*/

#define TLSF_CAST(t, exp)    ((t) (exp))
#define TLSF_MIN(a, b)       ((a) < (b) ? (a) : (b))
#define TLSF_MAX(a, b)       ((a) > (b) ? (a) : (b))

/*
** Set assert macro, if it has not been provided by the user.
*/
#define COUNT_ARGS_IMPL(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10, COUNT, ...) COUNT
#define COUNT_ARGS(...) COUNT_ARGS_IMPL(__VA_ARGS__,10,9,8,7,6,5,4,3,2,1,0)

static int MyAssertFun(int parameterNum, ...)
{
    va_list args;
    int     iRet;

    va_start(args, parameterNum);

    /**
     *  ‘_Bool’ is promoted to ‘int’ when passed through ‘...’
     */
    if (1 == parameterNum) {
        iRet = va_arg(args, int);
    }
    else {
        iRet = va_arg(args, int);
        const char* str = va_arg(args, const char*);
        if (0 == iRet) {
            puts(str);
        }
    }

    va_end(args);
    return iRet;
}

/**
 * void assert(int expression);
 *
 * assert evaluates the expression expression. If its value is false
 * (that is, 0), it prints an error message to stderr and then terminates the
 * program by calling abort.
 */
#ifdef NDEBUG
#define TLSF_ASSERT(...)    {}
#define TLSF_ASSERT_VOID(...)   {}
#else
#define TLSF_ASSERT(...)                                                        \
    {                                                                           \
        int iRet = MyAssertFun(COUNT_ARGS(__VA_ARGS__), __VA_ARGS__);           \
        if (0 == iRet) {                                                        \
            return 0;                                                           \
        }                                                                       \
    }

#define TLSF_ASSERT_VOID(...)                                                   \
    {                                                                           \
        int iRet = MyAssertFun(COUNT_ARGS(__VA_ARGS__), __VA_ARGS__);           \
        if (0 == iRet) {                                                        \
            return;                                                             \
        }                                                                       \
    }
#endif

/*
** Static assertion mechanism.
*/

#define _tlsf_glue2(x, y) x ## y
#define _tlsf_glue(x, y) _tlsf_glue2(x, y)
#define TLSF_STATIC_ASSERT(exp) \
    typedef char _tlsf_glue(static_assert, __LINE__) [(exp) ? 1 : -1]

/* This code has been tested on 32- and 64-bit (LP/LLP) architectures. */
TLSF_STATIC_ASSERT(sizeof(int) * CHAR_BIT == 32);
TLSF_STATIC_ASSERT(sizeof(size_t) * CHAR_BIT >= 32);
TLSF_STATIC_ASSERT(sizeof(size_t) * CHAR_BIT <= 64);

/* SL_INDEX_COUNT must be <= number of bits in sl_bitmap's storage type. */
TLSF_STATIC_ASSERT(sizeof(unsigned int) * CHAR_BIT >= (size_t)SL_INDEX_COUNT);

/* Ensure we've properly tuned our sizes. */
TLSF_STATIC_ASSERT((size_t)ALIGN_SIZE ==
                            (size_t)SMALL_BLOCK_SIZE / (size_t)SL_INDEX_COUNT);

/*
** Data structures and associated constants.
*/
typedef struct tagStaticMem {
    void*   mem;
    size_t  size;
#ifdef __DEBUG__
    size_t  applyCount;
#endif
    // Members that cannot be aligned with the size_t are placed at the end
    bool    inUse;
} StaticMem;

typedef struct tagPoolMemInfo {
    void*   mem;
    size_t  size;
} PoolMemInfo;

/*
** Block header structure.
**
** There are several implementation subtleties involved:
** - The prev_phys_block field is only valid if the previous block is free.
** - The prev_phys_block field is actually stored at the end of the
**   previous block. It appears at the beginning of this structure only to
**   simplify the implementation.
** - The next_free / prev_free fields are only valid if the block is free.
*/
typedef struct block_header_t
{
    /* Points to the previous physical block. */
    struct block_header_t* prev_phys_block;

    /* The size of this block, excluding the block header. */
    size_t size;

    /* Next and previous free blocks. */
    struct block_header_t* next_free;
    struct block_header_t* prev_free;
} block_header_t;

/*
** Since block sizes are always at least a multiple of 4, the two least
** significant bits of the size field are used to store the block status:
** - bit 0: whether block is busy or free
** - bit 1: whether previous block is busy or free
*/
static const size_t block_header_free_bit = (1 << 0);
static const size_t block_header_prev_free_bit = (1 << 1);

/*
** The size of the block header exposed to used blocks is the size field.
** The prev_phys_block field is stored *inside* the previous free block.
*/
static const size_t block_header_overhead = sizeof(size_t);

/* User data starts directly after the size field in a used block. */
static const size_t block_start_offset =
                                offsetof(block_header_t, size) + sizeof(size_t);

/*
** A free block must be large enough to store its header minus the size of
** the prev_phys_block field, and no larger than the number of addressable
** bits for FL_INDEX.
*/
static const size_t BLOCK_SIZE_MIN =
                               sizeof(block_header_t) - sizeof(block_header_t*);
static const size_t BLOCK_SIZE_MAX = TLSF_CAST(size_t, 1) << FL_INDEX_MAX;


/* The TLSF control structure. */
typedef struct control_t
{
    /* Empty lists point at this block to indicate they are free. */
    block_header_t block_null;

    /* Bitmaps for free lists. */
    unsigned int fl_bitmap;
    unsigned int sl_bitmap[(int)FL_INDEX_COUNT];

    /* Head of free lists. */
    block_header_t* blocks[(int)FL_INDEX_COUNT][(int)SL_INDEX_COUNT];

    StaticMem   staticMem[STATIC_MEM_NUM];
    size_t      numStaticMem;

    PoolMemInfo poolMemInfo[MAX_MEM_BLOCK_IN_POOL];
    size_t      numPoolMemInfo;

    size_t      total_size;
} control_t;

/* A type used for casting when doing pointer arithmetic. */
typedef ptrdiff_t tlsfptr_t;

/*
** block_header_t member functions.
*/

static size_t block_size(const block_header_t* block)
{
    return block->size & ~(block_header_free_bit | block_header_prev_free_bit);
}

static void block_set_size(block_header_t* block, size_t size)
{
    const size_t oldsize = block->size;

    block->size = (size | (oldsize & (block_header_free_bit |
                                                  block_header_prev_free_bit)));
}

static int block_is_last(const block_header_t* block)
{
    return block_size(block) == 0;
}

static int block_is_free(const block_header_t* block)
{
    return TLSF_CAST(int, block->size & block_header_free_bit);
}

static void block_set_free(block_header_t* block)
{
    block->size |= block_header_free_bit;
}

static void block_set_used(block_header_t* block)
{
    block->size &= ~block_header_free_bit;
}

static int block_is_prev_free(const block_header_t* block)
{
    return TLSF_CAST(int, block->size & block_header_prev_free_bit);
}

static void block_set_prev_free(block_header_t* block)
{
    block->size |= block_header_prev_free_bit;
}

static void block_set_prev_used(block_header_t* block)
{
    block->size &= ~block_header_prev_free_bit;
}

static block_header_t* block_from_ptr(const void* ptr)
{
    return TLSF_CAST(block_header_t*,
                     TLSF_CAST(unsigned char*, ptr) - block_start_offset);
}

static void* block_to_ptr(const block_header_t* block)
{
    return TLSF_CAST(void*,
                     TLSF_CAST(unsigned char*, block) + block_start_offset);
}

/* Return location of next block after block of given size. */
static block_header_t* offset_to_block(const void* ptr, size_t size)
{
    return TLSF_CAST(block_header_t*, TLSF_CAST(tlsfptr_t, ptr) + size);
}

/* Return location of previous block. */
static block_header_t* block_prev(const block_header_t* block)
{
    TLSF_ASSERT(block_is_prev_free(block), "previous block must be free");
    return block->prev_phys_block;
}

/* Return location of next existing block. */
static block_header_t* block_next(const block_header_t* block)
{
    block_header_t* next = offset_to_block(block_to_ptr(block),
                                     block_size(block) - block_header_overhead);
    TLSF_ASSERT(! block_is_last(block));
    return next;
}

/* Link a new block with its physical neighbor, return the neighbor. */
static block_header_t* block_link_next(block_header_t* block)
{
    block_header_t* next = block_next(block);
    next->prev_phys_block = block;
    return next;
}

static void block_mark_as_free(block_header_t* block)
{
    /* Link the block to the next block, first. */
    block_header_t* next = block_link_next(block);
    block_set_prev_free(next);
    block_set_free(block);
}

static void block_mark_as_used(block_header_t* block)
{
    block_header_t* next = block_next(block);
    block_set_prev_used(next);
    block_set_used(block);
}

static size_t align_up(size_t x, size_t align)
{
    if (0 != (align & (align - 1))) {
        // must align to a power of two
        align = BLOCK_SIZE_MAX;
    }

    return (x + (align - 1)) & ~(align - 1);
}

static size_t align_down(size_t x, size_t align)
{
    if (0 != (align & (align - 1))) {
        // must align to a power of two
        align = BLOCK_SIZE_MAX;
    }

    return x - (x & (align - 1));
}

static void* align_ptr(const void* ptr, size_t align)
{
    const tlsfptr_t aligned =
                       (TLSF_CAST(tlsfptr_t, ptr) + (align - 1)) & ~(align - 1);
    if (0 != (align & (align - 1))) {
        // must align to a power of two
        return NULL;
    }

    return TLSF_CAST(void*, aligned);
}

/*
** Adjust an allocation size to be aligned to word size, and no smaller
** than internal minimum.
*/
static size_t adjust_request_size(size_t size, size_t align)
{
    size_t adjust = 0;
    if (0 != size) {
        const size_t aligned = align_up(size, align);

        // aligned sized must not exceed BLOCK_SIZE_MAX or we'll go out of
        // bounds on sl_bitmap
        if (aligned < BLOCK_SIZE_MAX) {
            adjust = TLSF_MAX(aligned, BLOCK_SIZE_MIN);
        }
    }
    return adjust;
}

/*
** TLSF utility functions. In most cases, these are direct translations of
** the documentation found in the white paper.
*/

static void mapping_insert(size_t size, int* fli, int* sli)
{
    int fl, sl;
    if (size < (size_t)SMALL_BLOCK_SIZE) {
        /* Store small blocks in first list. */
        fl = 0;
        sl = TLSF_CAST(int, size) / ((int)SMALL_BLOCK_SIZE / (int)SL_INDEX_COUNT);
    }
    else {
        fl = tlsf_fls_sizet(size);
        sl = TLSF_CAST(int, size >>
                (fl - (int)SL_INDEX_COUNT_LOG2)) ^ (1 << (int)SL_INDEX_COUNT_LOG2);
        fl -= ((int)FL_INDEX_SHIFT - 1);
    }
    *fli = fl;
    *sli = sl;
}

/* This version rounds up to the next block size (for allocations) */
static void mapping_search(size_t size, int* fli, int* sli)
{
    if (size >= (size_t)SMALL_BLOCK_SIZE) {
        const size_t round = (1 << (tlsf_fls_sizet(size) -
                                              (size_t)SL_INDEX_COUNT_LOG2)) - 1;
        size += round;
    }
    mapping_insert(size, fli, sli);
}

static block_header_t* search_suitable_block(control_t* control, int* fli, int* sli)
{
    int fl = *fli;
    int sl = *sli;

    /*
    ** First, search for a block in the list associated with the given
    ** fl/sl index.
    */
    unsigned int sl_map = control->sl_bitmap[fl] & (~0U << sl);
    if (0 == sl_map) {
        /* No block exists. Search in the next largest first-level list. */
        const unsigned int fl_map = control->fl_bitmap & (~0U << (fl + 1));
        if (0 == fl_map) {
            /* No free blocks available, memory has been exhausted. */
            return 0;
        }

        fl = tlsf_ffs(fl_map);
        *fli = fl;
        sl_map = control->sl_bitmap[fl];
    }
    TLSF_ASSERT(sl_map, "internal error - second level bitmap is null");
    sl = tlsf_ffs(sl_map);
    *sli = sl;

    /* Return the first block in the free list. */
    return control->blocks[fl][sl];
}

/* Remove a free block from the free list.*/
static void remove_free_block(control_t* control, block_header_t* block, int fl, int sl)
{
    block_header_t* prev = block->prev_free;
    block_header_t* next = block->next_free;
    TLSF_ASSERT_VOID(prev, "prev_free field can not be null");
    TLSF_ASSERT_VOID(next, "next_free field can not be null");
    next->prev_free = prev;
    prev->next_free = next;

    /* If this block is the head of the free list, set new head. */
    if (control->blocks[fl][sl] == block) {
        control->blocks[fl][sl] = next;

        /* If the new head is null, clear the bitmap. */
        if (next == &control->block_null) {
            control->sl_bitmap[fl] &= ~(1U << sl);

            /* If the second bitmap is now empty, clear the fl bitmap. */
            if (! control->sl_bitmap[fl]) {
                control->fl_bitmap &= ~(1U << fl);
            }
        }
    }
}

/* Insert a free block into the free block list. */
static void insert_free_block(control_t* control, block_header_t* block, int fl, int sl)
{
    block_header_t* current = control->blocks[fl][sl];
    TLSF_ASSERT_VOID(current, "free list cannot have a null entry");
    TLSF_ASSERT_VOID(block, "cannot insert a null entry into the free list");
    block->next_free = current;
    block->prev_free = &control->block_null;
    current->prev_free = block;

    TLSF_ASSERT_VOID(block_to_ptr(block) == align_ptr(block_to_ptr(block),
                             (size_t)ALIGN_SIZE), "block not aligned properly");
    /*
    ** Insert the new block at the head of the list, and mark the first-
    ** and second-level bitmaps appropriately.
    */
    control->blocks[fl][sl] = block;
    control->fl_bitmap |= (1U << fl);
    control->sl_bitmap[fl] |= (1U << sl);
}

/* Remove a given block from the free list. */
static void block_remove(control_t* control, block_header_t* block)
{
    int fl, sl;

    mapping_insert(block_size(block), &fl, &sl);
    remove_free_block(control, block, fl, sl);
}

/* Insert a given block into the free list. */
static void block_insert(control_t* control, block_header_t* block)
{
    int fl, sl;

    mapping_insert(block_size(block), &fl, &sl);
    insert_free_block(control, block, fl, sl);
}

static int block_can_split(block_header_t* block, size_t size)
{
    return block_size(block) >= sizeof(block_header_t) + size;
}

/* Split a block into two, the second of which is free. */
static block_header_t* block_split(block_header_t* block, size_t size)
{
    /* Calculate the amount of space left in the remaining block. */
    block_header_t* remaining =
            offset_to_block(block_to_ptr(block), size - block_header_overhead);

    const size_t remain_size = block_size(block) - (size + block_header_overhead);

    TLSF_ASSERT(block_to_ptr(remaining) == align_ptr(block_to_ptr(remaining),
                            (size_t)ALIGN_SIZE), "remaining block not aligned properly");

    TLSF_ASSERT(block_size(block) == remain_size + size + block_header_overhead);
    block_set_size(remaining, remain_size);
    TLSF_ASSERT(block_size(remaining) >= BLOCK_SIZE_MIN, "block split with invalid size");

    block_set_size(block, size);
    block_mark_as_free(remaining);

    return remaining;
}

/* Absorb a free block's storage into an adjacent previous free block. */
static block_header_t* block_absorb(block_header_t* prev, block_header_t* block)
{
    TLSF_ASSERT(!block_is_last(prev), "previous block can't be last");
    /* Note: Leaves flags untouched. */
    prev->size += block_size(block) + block_header_overhead;
    block_link_next(prev);
    return prev;
}

/* Merge a just-freed block with an adjacent previous free block. */
static block_header_t* block_merge_prev(control_t* control, block_header_t* block)
{
    if (block_is_prev_free(block)) {
        block_header_t* prev = block_prev(block);
        TLSF_ASSERT(prev, "prev physical block can't be null");
        TLSF_ASSERT(block_is_free(prev), "prev block is not free though marked as such");
        block_remove(control, prev);
        block = block_absorb(prev, block);
    }

    return block;
}

/* Merge a just-freed block with an adjacent free block. */
static block_header_t* block_merge_next(control_t* control, block_header_t* block)
{
    block_header_t* next = block_next(block);
    TLSF_ASSERT(next, "next physical block can't be null");

    if (block_is_free(next)) {
        TLSF_ASSERT(!block_is_last(block), "previous block can't be last");
        block_remove(control, next);
        block = block_absorb(block, next);
    }

    return block;
}

/* Trim any trailing block space off the end of a block, return to pool. */
static void block_trim_free(control_t* control, block_header_t* block, size_t size)
{
    TLSF_ASSERT_VOID(block_is_free(block), "block must be free");
    if (block_can_split(block, size)) {
        block_header_t* remaining_block = block_split(block, size);
        TLSF_ASSERT_VOID((NULL != remaining_block), "block_split return NULL");

        block_link_next(block);
        block_set_prev_free(remaining_block);
        block_insert(control, remaining_block);
    }
}

/* Trim any trailing block space off the end of a used block, return to pool. */
static void block_trim_used(control_t* control, block_header_t* block, size_t size)
{
    TLSF_ASSERT_VOID(!block_is_free(block), "block must be used");
    if (block_can_split(block, size)) {
        /* If the next block is free, we must coalesce. */
        block_header_t* remaining_block = block_split(block, size);
        TLSF_ASSERT_VOID((NULL != remaining_block), "block_split return NULL");

        block_set_prev_used(remaining_block);

        remaining_block = block_merge_next(control, remaining_block);
        TLSF_ASSERT_VOID((NULL != remaining_block), "block_merge_next return NULL");

        block_insert(control, remaining_block);
    }
}

static block_header_t* block_trim_free_leading(control_t* control, block_header_t* block, size_t size)
{
    block_header_t* remaining_block = block;
    if (block_can_split(block, size)) {
        /* We want the 2nd block. */
        remaining_block = block_split(block, size - block_header_overhead);
        TLSF_ASSERT((NULL != remaining_block), "block_split return NULL");

        block_set_prev_free(remaining_block);

        block_link_next(block);
        block_insert(control, block);
    }

    return remaining_block;
}

static block_header_t* block_locate_free(control_t* control, size_t size)
{
    int fl = 0;
    int sl = 0;
    block_header_t *block = NULL;

    if (0 != size) {
        mapping_search(size, &fl, &sl);

        /**
          * mapping_search can futz with the size, so for excessively large sizes
          * it can sometimes wind up with indices that are off the end of the
          * block array.
          * So, we protect against that here, since this is the only callsite of
          * mapping_search.
          * Note that we don't need to check sl, since it comes from a modulo
          * operation that guarantees it's always in range.
          */
        if (fl < (int)FL_INDEX_COUNT) {
            block = search_suitable_block(control, &fl, &sl);
        }
    }

    if (NULL != block) {
        TLSF_ASSERT(block_size(block) >= size);
        remove_free_block(control, block, fl, sl);
    }

    return block;
}

static void* block_prepare_used(control_t* control, block_header_t* block, size_t size)
{
    void* p = NULL;

    if (NULL != block) {
        TLSF_ASSERT(size, "size must be non-zero");

        block_trim_free(control, block, size);
        block_mark_as_used(block);
        p = block_to_ptr(block);
    }

    return p;
}

/* Clear structure and point all empty lists at the null block. */
static void control_construct(control_t* control)
{
    int i, j;

    control->block_null.next_free = &control->block_null;
    control->block_null.prev_free = &control->block_null;

    control->fl_bitmap = 0;
    for (i = 0;  i < (int)FL_INDEX_COUNT;  i++) {
        control->sl_bitmap[i] = 0;
        for (j = 0;  j < (int)SL_INDEX_COUNT;  j++) {
            control->blocks[i][j] = &control->block_null;
        }
    }

    control->numStaticMem = 0;
    control->numPoolMemInfo = 0;
    control->total_size = 0;
}

/*
** Debugging utilities.
*/

typedef struct integrity_t
{
    int prev_status;
    int status;
} integrity_t;

#define TLSF_INSIST(x,...) { TLSF_ASSERT(x,__VA_ARGS__); if (!(x)) { status--; } }
#define TLSF_INSIST_VOID(x,...) { TLSF_ASSERT_VOID(x,__VA_ARGS__); if (!(x)) { status--; } }

static void integrity_walker(void* ptr, size_t size, size_t used, void* user)
{
    block_header_t* block = block_from_ptr(ptr);
    integrity_t* integ = TLSF_CAST(integrity_t*, user);
    const int this_prev_status = block_is_prev_free(block) ? 1 : 0;
    const int this_status = block_is_free(block) ? 1 : 0;
    const size_t this_block_size = block_size(block);

    int status = 0;
    (void)used;
    TLSF_INSIST_VOID(integ->prev_status == this_prev_status, "prev status incorrect");
    TLSF_INSIST_VOID(size == this_block_size, "block size incorrect");

    integ->prev_status = this_status;
    integ->status += status;
}

static size_t TlsfPoolMemInfoInsert(control_t* control, void *mem, size_t size)
{
    if (control->numPoolMemInfo >= MAX_MEM_BLOCK_IN_POOL) {
        return 0;
    }

    control->poolMemInfo[control->numPoolMemInfo].mem = mem;
    control->poolMemInfo[control->numPoolMemInfo].size = size;
    control->numPoolMemInfo++;

    return size;
}

int tlsf_check(tlsf_t tlsf)
{
    int i, j;

    control_t* control = TLSF_CAST(control_t*, tlsf);
    int status = 0;

    /* Check that the free lists and bitmaps are accurate. */
    for (i = 0;  i < (int)FL_INDEX_COUNT;  i++) {
        for (j = 0;  j < (int)SL_INDEX_COUNT;  j++) {
            const int fl_map = control->fl_bitmap & (1U << i);
            const int sl_list = control->sl_bitmap[i];
            const int sl_map = sl_list & (1U << j);
            const block_header_t* block = control->blocks[i][j];

            /* Check that first- and second-level lists agree. */
            if (0 != fl_map) {
                TLSF_INSIST(!sl_map, "second-level map must be null");
            }

            if (0 != sl_map) {
                TLSF_INSIST(block == &control->block_null, "block list must be null");
                continue;
            }

            /* Check that there is at least one free block. */
            TLSF_INSIST(sl_list, "no free blocks in second-level map");
            TLSF_INSIST(block != &control->block_null, "block should not be null");

            while (block != &control->block_null) {
                int fli, sli;
                TLSF_INSIST(block_is_free(block), "block should be free");
                TLSF_INSIST(!block_is_prev_free(block), "blocks should have coalesced");
                TLSF_INSIST(!block_is_free(block_next(block)), "blocks should have coalesced");
                TLSF_INSIST(block_is_prev_free(block_next(block)), "block should be free");
                TLSF_INSIST(block_size(block) >= BLOCK_SIZE_MIN, "block not minimum size");

                mapping_insert(block_size(block), &fli, &sli);
                TLSF_INSIST(fli == i && sli == j, "block size indexed in wrong list");
                block = block->next_free;
            }
        }
    }

    return status;
}

#undef TLSF_INSIST

static void default_walker(void* ptr, size_t size, size_t used, void* user)
{
    (void)user;
    printf("\t%p %s size: %x (%p)\n", ptr, used ? "used" : "free",
                                       (unsigned int)size, block_from_ptr(ptr));
}

void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user)
{
    tlsf_walker pool_walker;
    if (NULL != walker) {
        pool_walker = walker;
    }
    else {
        pool_walker = default_walker;
    }

    block_header_t* block = offset_to_block(pool, -(int)block_header_overhead);

    while ((NULL != block) && (! block_is_last(block))) {
        pool_walker(block_to_ptr(block),  block_size(block),
                                                  ! block_is_free(block), user);
        block = block_next(block);
    }
}

size_t tlsf_block_size(void* ptr)
{
    size_t size = 0;

    if (NULL != ptr) {
        const block_header_t* block = block_from_ptr(ptr);
        size = block_size(block);
    }

    return size;
}

int tlsf_check_pool(pool_t pool)
{
    /* Check that the blocks are physically correct. */
    integrity_t integ = { 0, 0 };
    tlsf_walk_pool(pool, integrity_walker, &integ);

    return integ.status;
}

/*
** Size of the TLSF structures in a given memory block passed to
** tlsf_create, equal to the size of a control_t
*/
size_t tlsf_size(void)
{
    return sizeof(control_t);
}

size_t tlsf_align_size(void)
{
    return (size_t)ALIGN_SIZE;
}

size_t tlsf_block_size_min(void)
{
    return BLOCK_SIZE_MIN;
}

size_t tlsf_block_size_max(void)
{
    return BLOCK_SIZE_MAX;
}

/*
** Overhead of the TLSF structures in a given memory block passed to
** tlsf_add_pool, equal to the overhead of a free block and the
** sentinel block.
*/
size_t tlsf_pool_overhead(void)
{
    return 2 * block_header_overhead;
}

size_t tlsf_alloc_overhead(void)
{
    return block_header_overhead;
}

pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes)
{
    if ((NULL == tlsf) || (NULL == mem) ||
                                (bytes < (tlsf_size() + (size_t)ALIGN_SIZE))) {
        return NULL;
    }

    block_header_t* block;
    block_header_t* next;

    const size_t pool_overhead = tlsf_pool_overhead();
    const size_t pool_bytes = align_down(bytes - pool_overhead, (size_t)ALIGN_SIZE);

    if (((ptrdiff_t)mem % (size_t)ALIGN_SIZE) != 0) {
        printf("tlsf_add_pool: Memory must be aligned by %u bytes.\n",
                                                    (unsigned int)ALIGN_SIZE);
        return NULL;
    }

    if ((pool_bytes < BLOCK_SIZE_MIN) || (pool_bytes > BLOCK_SIZE_MAX)) {
#if defined (TLSF_64BIT)
        printf("tlsf_add_pool: Memory size must be between 0x%x and 0x%x00 bytes.\n",
            (unsigned int)(pool_overhead + BLOCK_SIZE_MIN),
            (unsigned int)((pool_overhead + BLOCK_SIZE_MAX) / 256));
#else
        printf("tlsf_add_pool: Memory size must be between %u and %u bytes.\n",
            (unsigned int)(pool_overhead + BLOCK_SIZE_MIN),
            (unsigned int)(pool_overhead + BLOCK_SIZE_MAX));
#endif
        return NULL;
    }

    if (TlsfPoolMemInfoInsert(TLSF_CAST(control_t*, tlsf), mem, bytes) != bytes) {
        return 0;
    }

    /*
    ** Create the main free block. Offset the start of the block slightly
    ** so that the prev_phys_block field falls outside of the pool -
    ** it will never be used.
    */
    block = offset_to_block(mem, -(tlsfptr_t)block_header_overhead);
    block_set_size(block, pool_bytes);
    block_set_free(block);
    block_set_prev_used(block);
    block_insert(TLSF_CAST(control_t*, tlsf), block);

    /* Split the block to create a zero-size sentinel block. */
    next = block_link_next(block);
    block_set_size(next, 0);
    block_set_used(next);
    block_set_prev_free(next);

    TLSF_CAST(control_t*, tlsf)->total_size += pool_bytes;

    return mem;
}

void tlsf_remove_pool(tlsf_t tlsf, pool_t pool)
{
    if ((NULL == tlsf) || (NULL == pool)) {
        return;
    }

    control_t* control = TLSF_CAST(control_t*, tlsf);
    block_header_t* block = offset_to_block(pool, -(int)block_header_overhead);

    int fl = 0;
    int sl = 0;

    TLSF_ASSERT_VOID(block_is_free(block), "block should be free");
    TLSF_ASSERT_VOID(!block_is_free(block_next(block)), "next block should not be free");
    TLSF_ASSERT_VOID(block_size(block_next(block)) == 0, "next block size should be zero");

    mapping_insert(block_size(block), &fl, &sl);
    remove_free_block(control, block, fl, sl);
}

/*
** TLSF main interface.
*/

#if _DEBUG
int test_ffs_fls()
{
    /* Verify ffs/fls work properly. */
    int rv = 0;
    rv += (tlsf_ffs(0u) == -1) ? 0 : 0x1;
    rv += (tlsf_fls(0u) == -1) ? 0 : 0x2;
    rv += (tlsf_ffs(1u) == 0) ? 0 : 0x4;
    rv += (tlsf_fls(1u) == 0) ? 0 : 0x8;
    rv += (tlsf_ffs(0x80000000u) == 31) ? 0 : 0x10;
    rv += (tlsf_ffs(0x80008000u) == 15) ? 0 : 0x20;
    rv += (tlsf_fls(0x80000008u) == 31) ? 0 : 0x40;
    rv += (tlsf_fls(0x7FFFFFFFu) == 30) ? 0 : 0x80;

#if defined (TLSF_64BIT)
    rv += (tlsf_fls_sizet(0x80000000u) == 31) ? 0 : 0x100;
    rv += (tlsf_fls_sizet(0x100000000u) == 32) ? 0 : 0x200;
    rv += (tlsf_fls_sizet(0xffffffffffffffffu) == 63) ? 0 : 0x400;
#endif

    if (rv) {
        printf("test_ffs_fls: %x ffs/fls tests failed.\n", rv);
    }
    return rv;
}
#endif

tlsf_t tlsf_create(void* mem)
{
    if (NULL == mem) {
        return NULL;
    }

#if _DEBUG
    if (test_ffs_fls()) {
        return NULL;
    }
#endif

    if (((tlsfptr_t)mem % (size_t)ALIGN_SIZE) != 0) {
        /*
        printf("tlsf_create: Memory must be aligned to %u bytes.\n",
            (unsigned int)ALIGN_SIZE);
        */
        return NULL;
    }

    control_construct(TLSF_CAST(control_t*, mem));

    return TLSF_CAST(tlsf_t, mem);
}

tlsf_t tlsf_create_with_pool(void* mem, size_t bytes)
{
    if ((NULL == mem) || (bytes < (tlsf_size() + (size_t)ALIGN_SIZE))) {
        return NULL;
    }

    tlsf_t tlsf = tlsf_create(mem);
    if (NULL == tlsf) {
        return NULL;
    }

    if (tlsf_add_pool(tlsf, (char*)mem + tlsf_size(), bytes - tlsf_size()) == NULL) {
        return NULL;
    }

    return tlsf;
}

void tlsf_destroy(tlsf_t tlsf)
{
    /* Nothing to do. */
    (void)tlsf;
}

pool_t tlsf_get_pool(tlsf_t tlsf)
{
    return TLSF_CAST(pool_t, (char*)tlsf + tlsf_size());
}

void* tlsf_malloc(tlsf_t tlsf, size_t size)
{
    control_t* control = TLSF_CAST(control_t*, tlsf);
    if ((NULL == control) || (0 == size)) {
        return NULL;
    }

    const size_t adjust = adjust_request_size(size, ALIGN_SIZE);

    for (size_t i = 0;  i < control->numStaticMem;  i++) {
        StaticMem *staticMem = &(control->staticMem[i]);

        if ((! staticMem->inUse) && (NULL != staticMem->mem)) {
            if (staticMem->size == adjust) {
#ifdef __DEBUG__
                staticMem->applyCount++;
#endif
                staticMem->inUse = true;
                return staticMem->mem;
            }
        }
    }

    block_header_t* block = block_locate_free(control, adjust);
    void *p = block_prepare_used(control, block, adjust);
    if (NULL == p) {
        return NULL;
    }

    if (control->numStaticMem < STATIC_MEM_NUM) {
        StaticMem *staticMem = &(control->staticMem[control->numStaticMem]);

        staticMem->mem = p;
        staticMem->size = adjust;
        staticMem->inUse = true;
#ifdef __DEBUG__
        staticMem->applyCount = 1;
#endif
        control->numStaticMem++;
    }

    return p;
}

void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t size)
{
    control_t* control = TLSF_CAST(control_t*, tlsf);
    const size_t adjust = adjust_request_size(size, (size_t)ALIGN_SIZE);

    for (size_t i = 0;  i < control->numStaticMem;  i++) {
        StaticMem *staticMem = &(control->staticMem[i]);
        if ((! staticMem->inUse) && (NULL != staticMem->mem)) {
            if (staticMem->size == adjust) {
#ifdef __DEBUG__
                staticMem->applyCount++;
#endif
                staticMem->inUse = true;
                return staticMem->mem;
            }
        }
    }

    /*
    ** We must allocate an additional minimum block size bytes so that if
    ** our free block will leave an alignment gap which is smaller, we can
    ** trim a leading free block and release it back to the pool. We must
    ** do this because the previous physical block is in use, therefore
    ** the prev_phys_block field is not valid, and we can't simply adjust
    ** the size of that block.
    */
    const size_t gap_minimum = sizeof(block_header_t);
    const size_t size_with_gap = adjust_request_size(adjust + align + gap_minimum, align);

    /*
    ** If alignment is less than or equals base alignment, we're done.
    ** If we requested 0 bytes, return null, as tlsf_malloc(0) does.
    */
    size_t aligned_size;

    //  = (adjust && align > (size_t)ALIGN_SIZE) ? size_with_gap : adjust;
    if ((0 != adjust) && (align > (size_t)ALIGN_SIZE)) {
        aligned_size = size_with_gap;
    }
    else {
        aligned_size = adjust;
    }

    block_header_t* block = block_locate_free(control, aligned_size);

    /* This can't be a static assert. */
    TLSF_ASSERT(sizeof(block_header_t) == BLOCK_SIZE_MIN + block_header_overhead);

    if (NULL != block) {
        void* ptr = block_to_ptr(block);
        void* aligned = align_ptr(ptr, align);
        size_t gap = TLSF_CAST(size_t,
                     TLSF_CAST(tlsfptr_t, aligned) - TLSF_CAST(tlsfptr_t, ptr));

        /* If gap size is too small, offset to next aligned boundary. */
        if ((0 != gap) && (gap < gap_minimum)) {
            const size_t gap_remain = gap_minimum - gap;
            const size_t offset = TLSF_MAX(gap_remain, align);
            const void* next_aligned = TLSF_CAST(void*,
                                        TLSF_CAST(tlsfptr_t, aligned) + offset);

            aligned = align_ptr(next_aligned, align);
            gap = TLSF_CAST(size_t,
                     TLSF_CAST(tlsfptr_t, aligned) - TLSF_CAST(tlsfptr_t, ptr));
        }

        if (0 != gap) {
            TLSF_ASSERT(gap >= gap_minimum, "gap size too small");
            block = block_trim_free_leading(control, block, gap);
            TLSF_ASSERT((NULL != block), "block_trim_free_leading return NULL");
        }
    }

    void *p = block_prepare_used(control, block, adjust);
    if (NULL == p) {
        return NULL;
    }

    if (control->numStaticMem < STATIC_MEM_NUM) {
        StaticMem *staticMem = &(control->staticMem[control->numStaticMem]);

        staticMem->size = adjust;
        staticMem->inUse = true;
#ifdef __DEBUG__
        staticMem->applyCount = 1;
#endif
        control->numStaticMem++;
    }

    return p;
}

void *tlsf_free(tlsf_t tlsf, void* ptr)
{
    // Don't attempt to free a NULL pointer.
    if (NULL == ptr) {
        return NULL;
    }

    control_t* control = TLSF_CAST(control_t*, tlsf);
    size_t i;

    /**
     * Check whether ptr is in the memory pool.
     */
    for (i = 0;  i < control->numPoolMemInfo;  i++) {
        void *mem = control->poolMemInfo[i].mem;
        size_t size = control->poolMemInfo[i].size;
        if ((ptr >= mem) && ((char *)ptr < ((char *)mem + size))) {
            break;
        }
    }

    if (i < control->numPoolMemInfo) {
    // in the memory pool.
        for (i = 0;  i < control->numStaticMem;  i++) {
            StaticMem *staticMem = &(control->staticMem[i]);
            if ((staticMem->inUse) && (ptr == staticMem->mem)) {
                staticMem->inUse = false;
                return ptr;
            }
        }
    }
    else {
        // ptr not in any known pool: invalid free.
        // In debug: abort with useful message. In release: return NULL and log.
#ifndef NDEBUG
        fprintf(stderr, "tlsf_free: pointer %p not in any pool\n", ptr);
        abort();
#else
        return NULL;
#endif
    }

    block_header_t* block = block_from_ptr(ptr);
    if (block_is_free(block)) {
        // block already marked as free
        return NULL;
    }

    block_mark_as_free(block);
    block = block_merge_prev(control, block);
    TLSF_ASSERT((NULL != block), "block_merge_prev return NULL");
    block = block_merge_next(control, block);
    TLSF_ASSERT((NULL != block), "block_merge_next return NULL");
    block_insert(control, block);

    return ptr;
}

/*
** The TLSF block information provides us with enough information to
** provide a reasonably intelligent implementation of realloc, growing or
** shrinking the currently allocated block as required.
**
** This routine handles the somewhat esoteric edge cases of realloc:
** - a non-zero size with a null pointer will behave like malloc
** - a zero size with a non-null pointer will behave like free
** - a request that cannot be satisfied will leave the original buffer
**   untouched
** - an extended buffer size will leave the newly-allocated area with
**   contents undefined
*/
void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size)
{
    if (NULL == tlsf) {
        return NULL;
    }

    control_t* control = TLSF_CAST(control_t*, tlsf);
    void* p = NULL;

    /* Zero-size requests are treated as free. */
    if ((NULL != ptr) && (0 == size)) {
        tlsf_free(tlsf, ptr);
    }
    /* Requests with NULL pointers are treated as malloc. */
    else if (NULL == ptr) {
        p = tlsf_malloc(tlsf, size);
    }
    else {
        block_header_t* block = block_from_ptr(ptr);
        block_header_t* next = block_next(block);

        const size_t cursize = block_size(block);
        const size_t combined = cursize + block_size(next) + block_header_overhead;
        const size_t adjust = adjust_request_size(size, (size_t)ALIGN_SIZE);

        TLSF_ASSERT(!block_is_free(block), "block already marked as free");

        /*
        ** If the next block is used, or when combined with the current
        ** block, does not offer enough space, we must reallocate and copy.
        */
        if (adjust > cursize && (!block_is_free(next) || adjust > combined)) {
            p = tlsf_malloc(tlsf, size);
            if (NULL != p) {
                const size_t minsize = TLSF_MIN(cursize, size);
                memcpy(p, ptr, minsize);
                tlsf_free(tlsf, ptr);
            }
        }
        else {
            /* Do we need to expand to the next block? */
            if (adjust > cursize) {
                block_merge_next(control, block);
                block_mark_as_used(block);
            }

            /* Trim the resulting block and return the original pointer. */
            block_trim_used(control, block, adjust);
            p = ptr;
        }
    }

    return p;
}

static size_t walk_used_memory(void* pool)
{
    block_header_t* block = offset_to_block(pool, tlsf_pool_overhead());
    size_t used = 0;

    while (! block_is_last(block)) {
        if (! block_is_free(block)) {
            used += block_size(block);
        }
        block = block_next(block);
    }
    return used;
}

size_t tlsf_used_size(tlsf_t tlsf)
{
    return walk_used_memory(TLSF_CAST(control_t*, tlsf));
}

size_t tlsf_total_size(tlsf_t tlsf)
{
    return TLSF_CAST(control_t*, tlsf)->total_size;
}
